package com.xiongjie.humanTask;

import com.xiongjie.humanTask.jobworker.HumanTaskJobWorker;
import com.xiongjie.humanTask.service.PgService;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.api.RequestParameters;
import io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory;
import io.zeebe.client.ZeebeClient;

public class HumanTaskVertx extends AbstractVerticle {

    ZeebeClient client;
    PgService pgService;

    @Override
    public void start() {
        //1.初始化zeebeClient
        client = ZeebeClient
                .newClientBuilder()
                .brokerContactPoint("localhost:26500")
                .build();

        //初始化PgService
        pgService = new PgService(vertx);

        //2.部署一个jobworker,人工任务如果做成公共模块，则不能够在代码中写死jobworker需要获取的参数。
        HumanTaskJobWorker humanTaskJobWorker = new HumanTaskJobWorker(pgService);
        client.newWorker()
                .jobType("human")
                .handler(humanTaskJobWorker)
                .open();

        //3.启动一个webServer
        Router router = Router.router(vertx);

        //1.创建routerfactory
        OpenAPI3RouterFactory.create(vertx, "humanTaskOpenApi.yml", ar -> {
            if (ar.succeeded()) {
                OpenAPI3RouterFactory routerFactory = ar.result();

                routerFactory.addHandlerByOperationId("humanTask", context -> {
                    RequestParameters params = context.get("parsedParameters");
                    Long jobkey = params.pathParameter("jobKey").getLong();

                    if (jobkey != null) {
                        JsonObject body = params.body().getJsonObject();
                        pgService.findById(jobkey).setHandler(v -> {
                            if (v.succeeded()) {
                                client.newCompleteCommand(jobkey).variables(body.encode()).send().join();
                                pgService.updateState(v.result());

                                String res = jobkey + "人工任务执行完成";
                                context.response().end(res);
                            } else {
                                new RuntimeException("No task found with key: " + jobkey);
                            }
                        });
                    }
                });
                router.mountSubRouter("/xj", routerFactory.getRouter());
                vertx.createHttpServer()
                        .requestHandler(router)
                        .listen(8888);
            } else {
                System.out.println("加载api文件失败：" + ar.cause());
            }
        });
    }
}
